$(function(){
	// var key = getcookie('doutingshop');
	// if(key==''){
	// 	window.location.href = WapSiteUrl+'/tmpl/member/login.html';
	// }
    var state = GetQueryString('state');
    if (!state) {
        state='';
    };
	var pagesize =100;
	var curpage = 1;
	var hasMore = true;

    var readytopay = true;

	function initPage(pagesize){
		$.ajax({
			type:'post',
            url:ApiUrl+"/user/eb/getOrderPage",
            data:{page:curpage,rows:pagesize,state:state},
			dataType:'json',
			success:function(result){
				checklogin(result.rspCode);//检测是否登录了
				var data = result;
                if (curpage*pagesize<result.total) {
                    data.hasmore = true;
                } else{
                    data.hasmore = false;//是不是可以用下一页的功能，传到页面里去判断下一页是否可以用
                };
				
				data.WapSiteUrl = WapSiteUrl;//页面地址
				data.curpage = curpage;//当前页，判断是否上一页的disabled是否显示
				data.ApiUrl = ApiUrl;
				data.key = getcookie('doutingshop');
				template.helper('$getLocalTime', function (nS) {
                    var d = new Date(parseInt(nS));
                    var s = '';
                    s += d.getFullYear() + '年';
                    s += (d.getMonth() + 1) + '月';
                    s += d.getDate() + '日 ';
                    if (d.getHours()<10) {
                        s += '0'+d.getHours() + ':'; 
                    } else {
                        s += d.getHours() + ':';
                    }
                    
                    if (d.getMinutes()<10) {
                        s += '0'+d.getMinutes(); 
                    } else {
                        s += d.getMinutes();
                    }
                    return s;
				});
                template.helper('p2f', function(s) {
                    return (parseFloat(s) || 0).toFixed(2);
                });
                console.log(data);
                
				var html = template.render('order-list-tmpl', data);
				$("#order-list").html(html);
                if (!browser.versions.weixin){//app
                    // $('.payWeixin').hide();
                    $('.payAlipay').show();
                }else{//微信
                    // $('.payWeixin').show();
                    $('.payAlipay').hide();
                };
				//取消订单
				$(".cancel-order").click(cancelOrder);
				//下一页
				$(".next-page").click(nextPage);
				//上一页
				$(".pre-page").click(prePage);
				//确认订单
				$(".sure-order").click(sureOrder);

                $('.viewdelivery-order').click(viewOrderDelivery);

                $('.check-payment').click(function() {
                    if (!readytopay) {
                        $.sDialog({
                            skin:"red",
                            content:'暂无可用的支付方式',
                            okBtn:false,
                            cancelBtn:false
                        });
                        return false;
                    }
                });
                $(window).scrollTop(0);
			}
		});

        // $.ajax({
        //     type:'get',
        //     url:ApiUrl+"/index.php?act=member_payment&op=payment_list",
        //     data:{key:key},
        //     dataType:'json',
        //     success:function(result){
        //         $.each((result && result.datas && result.datas.payment_list) || [], function(k, v) {
        //             // console.log(v);
        //             if (v != '') {
        //                 readytopay = true;
        //                 return false;
        //             }
        //         });
        //     }
        // });
	}
	//初始化页面
	initPage(pagesize);

	//下一页
	function nextPage (){
		var self = $(this);
		var hasMore = self.attr("has_more");
		if(hasMore == "true"){
			curpage = curpage+1;
			initPage(pagesize);
		}
	}
	//上一页
	function prePage (){
		var self = $(this);
		if(curpage >1){
			self.removeClass("disabled");
			curpage = curpage-1;
			initPage(pagesize);
		}
	}

    //取消订单
    function cancelOrder(){
        var order_id = $(this).attr("orderid");

        $.sDialog({
            content: '确定取消订单？',
            okFn: function() { cancelOrderId(order_id); }
        });
    }

    function cancelOrderId(order_id) {
        $.ajax({
            type:"post",
            url:ApiUrl+"/user/eb/delOrderById/"+order_id,
            data:{order_id:order_id},
            dataType:"json",
            success:function(result){
                console.log(result);
                if (!result.rspCode) {
                    $.sDialog({
                        skin:"red",
                        content:'取消订单成功',
                        okBtn:false,
                        cancelBtn:false
                    });
                     setTimeout(function(){
                         location.href = WapSiteUrl+'/tmpl/member/order_list.html?state=0';
                     },500)
                    // console.log($(a [orderid = order_id]).first());
                    // // //.parentsUntil("li").hide(1000);
                }else{
                    $.sDialog({
                        skin:"red",
                        content:'取消订单失败',
                        okBtn:false,
                        cancelBtn:false
                    });
                }
            }
        });
    }
    $('.del-order').live('click',function(){
        var order_id = $(this).attr("orderid");
        cancelOrderId(order_id);
    });
    // 余额支付
    $('.balance-pay').live('click',function(){
        var order_id = $(this).attr('orderid')
        $.ajax({
            url: ApiUrl + "/user/eb/orderPay/"+order_id,
            type: "post",
            dataType: "json",
            success: function (result) {
                checklogin(result.rspCode);//检测是否登录了
                console.log(result);
                if (!result.rspCode) {
                    $.sDialog({
                        skin:"red",
                        content:'支付成功',
                        okBtn:false,
                        cancelBtn:false
                    });
                    setTimeout(function(){
                        location.href = WapSiteUrl+'/tmpl/member/order_list.html?state=1';
                    },2100)
                }else{
                    $.sDialog({
                        skin:"red",
                        content:'余额不足,请先充值后再支付',
                        okBtn:false,
                        cancelBtn:false
                    });
                }
            }
        })
    });

    // 支付宝支付
    $('.payAlipay').live('click',function(){
        var payEle = $('.payAlipay');
        setupWebViewJavascriptBridge(function(bridge) {
            // var uniqueId = 1
            // if (browser.versions.android) {
            //     bridge.init(function(message, responseCallback) {
            //         var data = {'init': 'init'};
            //         responseCallback(data);
            //     });
            // }
            bridge.registerHandler('AlipayPayFromAppJavascriptHandle', function(data, responseCallback) {
                var responseData = { 'Javascript Says':'Right back atcha!' }
                responseCallback(responseData)
            })

            bridge.callHandler('needAlipayPayFromAppCallback', {'orderid':payEle.attr('orderid')}, function(response) {
                
            })
        })
    });

    // 微信支付
    $('.payWeixin').live('click',function(){
        var order_id = $(this).attr('orderid');
        if (!browser.versions.weixin){//app
            var payEle = $('.payAlipay');
            setupWebViewJavascriptBridge(function(bridge) {
                bridge.registerHandler('weixinPayFromAppJavascriptHandle', function(data, responseCallback) {
                    var responseData = { 'Javascript Says':'Right back atcha!' }
                    responseCallback(responseData)
                })

                bridge.callHandler('needWeiXinPayFromAppCallback', {'orderid':payEle.attr('orderid')}, function(response) {
                    
                })
            });
        }else{//微信
            callpay(order_id);
        };
        
    });

    function callpay(orderid){
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
                document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
            }
        }else{
            jsApiCall(orderid);
        }
    }
    function jsApiCall(jsApiParameters){
        $.ajax({
            url: ApiUrl + "/user/eb/weixinPayGetParame/"+jsApiParameters,
            type: "post",
            dataType: "json",
            success: function (result) {
                checklogin(result.rspCode);//检测是否登录了
                // console.log(result)
                // console.log({
                //            "appId" : result.appId,     //公众号名称，由商户传入     
                //            "timeStamp":""+result.timeStamp,         //时间戳，自1970年以来的秒数     
                //            "nonceStr" : result.nonceStr, //随机串     
                //            "package" : result.package,     
                //            "signType" : "MD5",         //微信签名方式:     
                //            "paySign" : result.paySign //微信签名 
                //        })
                if (result.rspCode==0) {
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest',
                        {
                           "appId" : result.appId,     //公众号名称，由商户传入     
                           "timeStamp":""+result.timeStamp,         //时间戳，自1970年以来的秒数     
                           "nonceStr" : result.nonceStr, //随机串     
                           "package" : result.package,     
                           "signType" : "MD5",         //微信签名方式:     
                           "paySign" : result.paySign //微信签名
                       },
                        function(res){
                          if (res.err_msg=="get_brand_wcpay_request:ok") {//支付成功
                            $.sDialog({
                                skin:"red",
                                content:'支付成功',
                                okBtn:false,
                                cancelBtn:false
                            });
                            setTimeout(function(){
                                location.href = WapSiteUrl+'/tmpl/member/order_list.html?state=1';
                            },2100)
                          }else if(res.err_msg=="get_brand_wcpay_request:cancel"){
                            $.sDialog({
                                skin:"red",
                                content:'微信支付失败：用户取消',
                                okBtn:false,
                                cancelBtn:false
                            });
                          }else{
                            $.sDialog({
                                skin:"red",
                                content:'微信支付失败：遇到错误',
                                okBtn:false,
                                cancelBtn:false
                            });
                          }
                        }
                    );
                }else{
                    $.sDialog({
                        skin:"red",
                        content:result.rspDesc,
                        okBtn:false,
                        cancelBtn:false
                    });
                }
            }
        })
    }

    //确认订单
    function sureOrder(){
        var order_id = $(this).attr("order_id");

        $.sDialog({
            content: '确定确认订单？',
            okFn: function() { sureOrderId(order_id); }
        });
    }

    function sureOrderId(order_id) {
        $.ajax({
            type:"post",
            url:ApiUrl+"/index.php?act=member_order&op=order_receive",
            data:{order_id:order_id,key:key},
            dataType:"json",
            success:function(result){
                if(result.datas && result.datas == 1){
                    initPage(pagesize);
                }
            }
        });
    }

    function viewOrderDelivery() {
        var orderId = $(this).attr('order_id');
        location.href = WapSiteUrl + '/tmpl/member/order_delivery.html?order_id=' + orderId;
    }
});
